<?php

namespace app\shop\logic;

use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;
use think\facade\Config;
use think\facade\Db;
use Throwable;
use app\shop\model\ShopsModel;
use app\data\util\HttpUtil;
use think\facade\Cache;

class ShopLogic
{
    protected $model = null;

    public function __construct()
    {
        $this->model = new ShopsModel();
    }

    public function getShopsList($params = [])
    {

        $shop_id   = $params['shop_id'] ?? '';
        $region    = $params['region'] ?? '';
        $limit     = $params['limit'] ?? 10;

        $where = [];
        $order = [];
        if ($shop_id) {
            $where[] = ['id', '=', $shop_id];
        }

        if ($region) {
            $where[] = ['region', 'like', '%' . $region . '%'];
        }

        $res = $this->model
            ->field('id,name as shop_name,region,seller_type,status,user_id')
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $list = $res->items()?:[];
        $list = objectToArray($list);
        if($list){
             foreach($list as $k=>$v){
                 $user_info             = $v['user_id'] ? self::getUserInfo($v['user_id']):'';
                 $list[$k]['user_name'] = $user_info;
                 $list[$k]['start_time']= '';
                 $list[$k]['user_id']   = $v['user_id'] ? explode(',',$v['user_id']):'';
             }
        }

        $data = [
            'list'   => $list,
            'total'  => $res->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    /**
     * @desc获取店铺运营者
     * @date 2024-04-24
     */
    public function getUserInfo($user_id){
        //批量获取用户名称;
        $user_names     = Db::name('admin')->where('status','1')->field('id,username')->select()->toArray();
        $user_id        = explode(',',$user_id);
        $user_info      = Db::name('admin')
                           ->where('status','1')
                           ->whereIn('id',$user_id)
                           ->field('nickname')
                           ->select()
                           ->toArray();
        $user_info      = array_column($user_info,'nickname');
        return implode(',',$user_info);
    }








    /**
     * @desc 编辑店铺运营人员
     * @date 2024-04-12
     */
    public function editShopsList($params=[]){
        $id           = getIsset($params,'id');
        $status       = $params['status']??'normal';
        $user_id      = $params['user_id']??0;
        $start_time   = $params['start_time']??0;
        if(!$id) return json(DefaultResponse(200, true, 'ID不能为空!', ''));
        $shop_info    = Db::name('shops')->where('id',$id)->find();
        $exist_shops_user = Db::name('shops_user')->where('shop_id',$shop_info['id'])->order('id desc')->find();
        if($exist_shops_user){
            Db::name('shops_user')->where('id',$exist_shops_user['id'])->update(['bund_status'=>2,'end_time'=>strtotime($start_time)]);
        }
        $user_id = implode(',', $user_id);
        try {
            Db::startTrans(); // 开启事务
            //批量写入数据;
            Db::name('shops')->where('id',$id)->update(['user_id'=>$user_id,'status'=>$status]);
            Db::name('shops_user')->insert(
                [
                    'shop_id'    =>$shop_info['id'],
                    'user_id'    =>$user_id,
                    'start_time' =>strtotime($start_time),
                ]
            );
            Db::commit(); // 提交事务
            return json(DefaultResponse(200, true, '操作成功', ''));
        }
        catch (Exception $e) {
            Db::rollback(); // 回滚事务
            return json(DefaultResponse(200, true, $e->getMessage(), ''));
        }





    }












    /**
     * @desc  通过id获取店铺信息
     * @date  2024/3/21 0021
     * @param $shop_id
     * @return array|mixed
     * @author ligang
     */
    public function getShopInfoById($shop_id='')
    {
        $info = $this->model->find($shop_id);
        return  objectToArray($info);
    }


    /**
     * @desc  获取员工列表接口
     * @date  2024-04-12
     */
    public function getUserList(){
        $user_names = Db::name('admin')->where('status','1')->field('id,username')->select();
        return   json(DefaultResponse(200, true, '获取成功', objectToArray($user_names)));
    }


    /**
     * @desc  更新店铺信息
     * @date  2024/4/09
     * @author luckyXiong
     */
    public function updateShopToken(){
        $shops     = Db::name('shops')->where('status','normal')->select()->toArray();
        foreach($shops as  $v){
            //推动数据到队列;
            MqTaskPushLogic::mq_task_push(
                '',
                MqQueueName::QUEUE_TIKTOK_SHOP_TOKEN_UPDATE_QUEUE,
                $v,
                false
            );
        }
        return json(DefaultResponse(200, true, '操作成功', null));
    }

    /**
     * @desc  定时更新金蚁token缓存在redis中
     * @date  2024/4/12
     * @author luckyXiong
     */
    public function updateJINYIToken(){
        $data = [
            'AppID'   => 1002,
            'AppKey'  => 'abcdefgh',
        ];
        $base_url   = Config('Logisticskey.JY.url');
        $token_path = Config('Logisticskey.JY.create_token_path');
        $url        = $base_url.$token_path;
        $res        = HttpUtil::postDataCurl($url, $data);
        //更新token
        Db::name('jinyi_token')->where('id', 1)->update(
            ['token' => $res['Data']]
        );
        //2024-07-11 同步到shopify
        $url    = Config('Logisticskey.shopify_computer.base_url').'order/OrderList/jinyiToken';
        HttpUtil::postDataCurl($url, ['token'=>$res['Data']]);
    }



    /**
     * @desc 更新店铺信息
     * @date  2024/4/09
     * @author luckyXiong
     */
    public function updateShopInfo($params=[]){
        $shop   = $params;
        $url    = Config('Logisticskey.shop.refresh_token_url');
        $url    = $url."?app_key=" . $shop['app_key'] . "&app_secret=" . $shop['app_secret'] . "&refresh_token=" . $shop['refresh_token'] . "&grant_type=refresh_token";
        $return = HttpUtil::tikGetUrl($url, $shop['access_token']);
        if (isset($return['data']) && !empty($return['data'])) {
            $row  = [
                'access_token'           => $return['data']['access_token'],
                'access_token_expire_in' => $return['data']['access_token_expire_in'],
                'refresh_token'          => $return['data']['refresh_token'],
            ];
            $this->model->where('id', $shop['id'])->update($row);
        }
        return true;
    }

    /**
     * @desc 更新店铺名称
     */
    public function updateShopName($params=[]){
        $shops = Db::name('shops')->select()->toarray();
        if(!empty($shops)){
            foreach ($shops as $k=>$shop) {
                $this->updateShopNameInfo($shop);
            }
        }
        return json(DefaultResponse(200, true, '操作成功!'));
    }

    /**
     * @desc 更新店铺名称
     */
    public function updateShopNameInfo($shop=[]){
        $path   = Config('Logisticskey.shop.get_shop_url');
        $url    = Config('Logisticskey.TIKTOK.basic_url');
        $sign = $shop['app_secret'] . '' . $path . 'app_key' . $shop['app_key'] . 'timestamp' . time() . '' . $shop['app_secret'];
        $sign = hash_hmac('sha256', $sign, $shop['app_secret']);
        $url = $url . $path . "?app_key=" . $shop['app_key'] . "&sign=" . $sign . "&timestamp=" . time();
        $data = HttpUtil::tikGetUrl($url, $shop['access_token']);
        if(!empty($data)){
            if(isset($data['data']['shops']) && !empty($data['data']['shops'])){
                $shops = $data['data']['shops'];
                foreach ($shops as $ks=>$vs) {
                    $site = Db::name('shops')->where('shop_id',$vs['id'])->find();
                    if(!empty($site)){
                        $update = array();
                        $update['cipher'] = $vs['cipher'];
                        $update['name'] = $vs['name'];
                        $update['region'] = $vs['region'];
                        $update['seller_type'] = $vs['seller_type'];
                        Db::name('shops')->where('shop_id',$vs['id'])->update($update);
                    }
                }
            }
        }
        return true;
    }


    /**
     * @desc 店铺拖放排序
     * @date  2024/4/29
     * @author luckyXiong
     */
    public function sortable($params=[]){
        $id        = $params['id']??'';
        $targetId  = $params['targetId']??'';
        if($id){
            $this->model->where('id', $id)->update(['sort_id'=>$targetId]);
        }
        return json(DefaultResponse(200, true, '操作成功', null));
    }


}
